from django.shortcuts import render,get_object_or_404
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
# Create your views here.
from django.views.generic import ListView
from .models import Post,Comment
from .forms import EmailPostForm,CommentForm

class PostListView(ListView):
	queryset = Post.objects.all()
	context_object_name = "posts"
	paginate_by = 3
	template_name = 'blog/post/list.html'

def post_share(request,post_id):
	post = get_object_or_404(Post,id=post_id,status='publish')

	if request.method == 'POST':
		form = EmailPostForm(request.POST)
		if form.is_valid():
			cd  = form.cleaned_data
	else:
		form = EmailPostForm()
	return render(request,'blog/post/share.html',{'post':post,'form':form})

def post_list(request):
	object_list = Post.objects.all()
	paginator = Paginator(object_list,1)
	page = request.GET.get('page')
	try:
		posts = paginator.page(page)
	except PageNotAnInteger:
		posts = paginator.page(1)
	except EmptyPage:
		posts = paginator.page(paginator.num_pages)

	return render(request,
		'blog/post/list.html',
		{
			'posts':posts,
			'page' : page
		})

def post_detail(request,year,month,day,post):
	post = get_object_or_404(Post,
		status = 'publish',
		publish__year = year,
		publish__month = month,
		publish__day = day
		)

	comments = post.comments.filter(active=True) #related_name
	new_comment = None
	if request.method == 'POST':
		comment_form = CommentForm(request.POST)
		if comment_form.is_valid():
			new_comment = comment_form.save(commit=False)# 通过调用这个表单的save()方法创建一个新的Comment对象
			new_comment.post = post
			new_comment.save()
	else:
		comment_form = CommentForm()
	return render(request,'blog/post/detail.html',{
			'post' : post,
			'comments' : comments,
			'new_comment' : new_comment,
			'comment_form' : comment_form
		})

	return render(request,
			'blog/post/detail.html',
			{'post':post}
	)

